class ApprovalController < ApplicationController

  before_filter :login_required
  
  def index
    list
    render :action => 'list'
  end

  # GETs should be safe (see http://www.w3.org/2001/tag/doc/whenToUseGet.html)
  verify :method => :post, :only => [ :destroy, :create, :update ],
         :redirect_to => { :action => :list }

  def list
    @approval_pages, @approvals = paginate :approvals, :per_page => 10
  end

  def show
    @approval = Approval.find(params[:id])
  end

  def new
    @approval = Approval.new
  end

  def create
    @approval = Approval.new(params[:approval])
    if @approval.save
      flash[:notice] = 'Approval was successfully created.'
      redirect_to :action => 'list'
    else
      render :action => 'new'
    end
  end

  def edit
    @approval = Approval.find(params[:id], :include => [:submission])         
    
    if @approval.submission.data
      @submission_data = HashModel::Model.new(YAML::load(@approval.submission.data))
    else    
      @submission_data = HashModel::Model.new({})
    end
  end

  def update 
    
    if params[:commit] == "Cancel" 
      redirect_to :controller => 'workitem', :action => 'list'   
      return
    end
                
    # find approval record
    @approval = Approval.find(params[:id], :include => :submission) 
              
    # update record with values from form
    if @approval.update_attributes(params[:approval])
      
      # create flash notice
      flash[:notice] = 'Approval was successfully updated.'
      
      if @approval.approved and params[:more_approval]   
                
          # Add more approvers to the list
          params[:more_approval].each { |k,v|    
            if v and v != ""
              @approval.submission.add_approval(Manager.find(v))
            end
          }
        
      end 
      
      redirect_to :controller => 'workitem', :action => 'list'
    else
      render :action => 'edit'
    end
  end

  def destroy 
    if current_user.is_admin?
      Approval.find(params[:id]).destroy
    end
    redirect_to :action => 'list'
  end  
  
  def allow
    @approval = Approval.find(params[:id], :include => [:submission])
    @approval.submission.status = Status.find_or_create_by_name("Approved")
    @approval.complete = true  
    @approval.submission.save!
    @approval.save!
    User.find_admins.each { |admin|
      UserNotifier.deliver_waiting_judges(admin)
    }
    redirect_to :controller => 'workitem', :action => 'list'  
  end
  
  def deny
    @approval = Approval.find(params[:id], :include => [:submission])
    @approval.submission.status = Status.find_or_create_by_name("Not Approved")
    @approval.complete = true  
    @approval.submission.save!
    @approval.save!
    User.find_admins.each { |admin|
      UserNotifier.deliver_waiting_judges(admin)
    }
    redirect_to :controller => 'workitem', :action => 'list'  
  end   
end
